package pw.hais.video.controller

import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import pw.hais.video.entity.User
import pw.hais.video.repository.UserRepository
import javax.servlet.http.HttpServletRequest

@RestController
@RequestMapping("/user")
class UserController(val userRepository: UserRepository) {

    //增加 http://127.0.0.1:8080/user/add?userName=aaa&passWord=123456
    @RequestMapping("/add")
    fun add(userName: String, passWord: String): User {
        val user = User(null, userName, passWord)
        return userRepository.save(user)
    }

    //根据用户名查询用户  http://127.0.0.1:8080/user/findByName?userName=xxx
    @RequestMapping("/findByName")
    fun findByName(userName: String): List<User> {
        return userRepository.findByUserName(userName)
    }

    //根据ID查询用户   http://127.0.0.1:8080/user/findById/2
    @GetMapping("/findById/{id}")
    fun findById(@PathVariable("id") id: Long): User {
        return userRepository.findById(id).get()
    }

    //根据姓名查询用户 http://127.0.0.1:8080/user/all
    @GetMapping("/all")
    fun all(request: HttpServletRequest): String {
        val lists = userRepository.findAll()
        request.setAttribute("users", lists)
        return "/user/list"
    }

}